//
//  ReadBookVOrH_VC+Hang.m
//  KidReading
//
//  Created by telen on 16/3/8.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadBookVOrH_VC+Hang.h"
#import "ConstDefine.h"
#import "RecordOperationBubbleViewController.h"

@interface ReadBookVOrH_VC()
@property(nonatomic,strong)HangMenuForCover* hangMenus;
//
@property(nonatomic,strong)UIButton* readMySelf;
@property(nonatomic,strong)UIButton* readToMe;
@property(nonatomic,strong)UIButton* myDiy;
//
@property(nonatomic,assign)NSInteger lastUid;//登陆前
//
@end

@implementation ReadBookVOrH_VC (Hang)

ASSOCIATED(hangMenus, setHangMenus, HangMenuForCover*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(readMySelf, setReadMySelf, UIButton*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(readToMe, setReadToMe, UIButton*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(myDiy, setMyDiy, UIButton*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//
ASSOCIATED_NSInteger(lastUid, setLastUid);

+ (void)load
{
    [self swizzleSelector:@selector(dealloc_My_hang) withSelector:@selector(dealloc_My)];
    [self swizzleSelector:@selector(viewDidLoad) withSelector:@selector(viewDidLoad_hang)];
}

-(void)dealloc_My_hang{
    [self dealloc_My_hang];
    [[NetSyncRecord shareSingle] closeBook];
}

- (void)uinfoChanged_loginEnd:(NSNotification*)sender
{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    if (uinfo.uid != self.lastUid) {
        [DataProcessing do_Main:^{
            [self tapBack];
        } delay:2];
    }
}

- (void)viewDidLoad_hang
{
    [self viewDidLoad_hang];
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uinfoChanged_loginEnd:) name:ROOTVCUINFOCHANGED object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:ROOTVCUINFOCHANGED object:nil];
}

- (void)addHangMenu
{
    //
    NSNumber* book_mark = self.bookDict[@"book_mark"];
    if (book_mark && [book_mark isEqualToNumber:@(-1)]) {
        self.hangMenus = nil;
        return;
    }
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    //
    [[NetSyncRecord shareSingle] bookOpenInitUid:uinfo.uid BookId:self.bookid];
    //
    [[NetSyncRecord shareSingle] synaNetRecordsListWithUid:uinfo.uid BookId:self.bookid Success:nil Failure:nil];
    //
    HangMenuForCover* hangMenus = [HangMenuForCover hangMenuForCover];
    [self.view addSubview:hangMenus];
    self.hangMenus = hangMenus;
    //
    //readmyself
    NSString* stron = [DataProcessing languageForfileName:@"guide_btn_readmyself_normal_v2.png"];
    NSString* stroff = [DataProcessing languageForfileName:@"guide_btn_readmyself_highlight_v2.png"];
    CGRect frame = CGRectMake(0,0, ceil(110/ratio_w), ceil(75/ratio_w));
    UIButton* readmyself = [self getBtnWithFrame:frame normalpng:stron selectpng:stroff];
    self.readMySelf = readmyself;
    //readtome
    stron = [DataProcessing languageForfileName:@"guide_btn_readtome_normal_v2.png"];
    stroff = [DataProcessing languageForfileName:@"guide_btn_readtome_highlight_v2.png"];
    frame = CGRectMake(0,0, ceil(110/ratio_w), ceil(75/ratio_w));
    UIButton*  readtome = [self getBtnWithFrame:frame normalpng:stron selectpng:stroff];
    self.readToMe = readtome;
    //Diy
    stron = @"btn_diy_normal.png";
    stroff = @"btn_diy_pressed.png";
    frame = CGRectMake(0,0, ceil(110/ratio_w), ceil(75/ratio_w));
    UIButton*  diy = [self getBtnWithFrame:frame normalpng:stron selectpng:stroff];
    self.myDiy = diy;
    //
    [hangMenus setMenuViewArr:@[readtome,readmyself]];
    //
    CGPoint pt = hangMenus.frameOrigin_show;
    CGFloat hang_w = hangMenus.frame.size.width;
    hangMenus.frameOrigin_show = CGPointMake(width_my-hang_w*1.2, pt.y);
    pt = hangMenus.frameOrigin_unshow;
    hangMenus.frameOrigin_unshow = CGPointMake(width_my+hang_w*1.2, pt.y);
    //
    frame = hangMenus.frame;
    frame.origin = hangMenus.frameOrigin_unshow;
    hangMenus.frame = frame;
    //
    [readmyself addTarget:self action:@selector(clickedReadMySelf) forControlEvents:UIControlEventTouchUpInside];
    [readtome addTarget:self action:@selector(clickedReadToMe) forControlEvents:UIControlEventTouchUpInside];
    [diy addTarget:self action:@selector(clickedDiy) forControlEvents:UIControlEventTouchUpInside];
}

- (UIButton*)getBtnWithFrame:(CGRect)frame normalpng:(NSString*)normal selectpng:(NSString*)select
{
    UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    UIImage* image = [UIImage imageNamed:normal];
    //[btn setImage:image forState:UIControlStateNormal];
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    image = [UIImage imageNamed:select];
    [btn setImage:image forState:UIControlStateHighlighted];
    [btn setBackgroundImage:image forState:UIControlStateHighlighted];
    [btn setBackgroundImage:image forState:UIControlStateSelected];
    [btn setExclusiveTouch:YES];
    
    return btn;
}

- (void)reflashHangMenus
{
    if(self.hangMenus)[self updateHangMenus];
    if (readView.currentPageView.pageIndex == 0){
        [self.hangMenus show];
        [UIApplication sharedApplication].idleTimerDisabled = NO;//关闭防止锁屏
    }else{
        [self.hangMenus unShow];
    }
}

- (void)updateHangMenus
{
    void(^flashMenus)(NSArray*) = ^(NSArray* arr){
        if (self.hangMenus.menuViewArr.count != arr.count) {
            [self.hangMenus setMenuViewArr:arr];
        }
    };
    //
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    //
    if ([[NetSyncRecord shareSingle] isBookRecordExistWithUid:uinfo.uid BookId:self.bookid]) {
        flashMenus(@[self.readToMe,self.readMySelf,self.myDiy]);
    }else{
        //
        [[NetSyncRecord shareSingle] isRecordExistOnNetWithUid:uinfo.uid BookId:self.bookid CheckComplete:^(BOOL isExist) {
            [DataProcessing do_Main_quick:^{
                if (isExist) {
                    flashMenus(@[self.readToMe,self.readMySelf,self.myDiy]);
                }else{
                    flashMenus(@[self.readToMe,self.readMySelf]);
                }
            }];
        }];
    }
}

- (void)clickedReadMySelf
{
    if (!handImageView) {
        UIImage* image = [UIImage imageNamed:@"public_hand.png"];
        handImageView = [[UIImageView alloc] initWithImage:image];
        [self.view addSubview:handImageView];
        CGPoint pt = CGPointMake(width_my-image.size.width*0.5, height_my*0.5);
        handImageView.center = pt;
        pt.x = width_my*0.5;
        handImageView.alpha = 0;
        [UIView animateKeyframesWithDuration:1.5f delay:0.0 options:UIViewKeyframeAnimationOptionLayoutSubviews animations:^{
            [UIView addKeyframeWithRelativeStartTime:0.0 relativeDuration:0.05f animations:^{
                handImageView.alpha = 1;
            }];
            [UIView addKeyframeWithRelativeStartTime:0.3f relativeDuration:0.5f animations:^{
                handImageView.center = pt;
            }];
            [UIView addKeyframeWithRelativeStartTime:0.9f relativeDuration:0.05f animations:^{
                handImageView.alpha = 0;
            }];
        } completion:^(BOOL finished) {
            [handImageView removeFromSuperview];
            handImageView = nil;
        }];
    }
    //telen 统计
    //[UMSAgent postEvent:@"Guide_clk_readmyself" label:self.bookName];
    //
    //阅读统计
    [[DBHelper shareInstance] addReadInfo_bookReadMode:self.bookid mode:RMode_ido];
    
    //statistical统计
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"自己读"] needReturnValue:NO];
}

- (void)clickedReadToMe
{
    //self.needPageMap = NO;
    self.isAutoRead = YES;
    [UIApplication sharedApplication].idleTimerDisabled = YES;//防止锁屏
    //
    indexMp3 = 0;
    [NSObject msgToTarget:self menthed:@"autoReaderIF" refs:nil needReturnValue:NO];
    //[self autoReaderIF];
    [self.hangMenus unShow];
    //telen 统计
    //[UMSAgent postEvent:@"Guide_clk_readme" label:self.bookName];
    //
    //阅读统计
    [[DBHelper shareInstance] addReadInfo_bookReadMode:self.bookid mode:RMode_forme];
    
    //statistical统计
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"为我读"] needReturnValue:NO];
}

- (void)playDiy
{
    [self msgTo_menthed:@"playMyRecord" refs:nil needReturnValue:NO];
    [DataProcess do_Main:^{
        [self.hangMenus unShow];
    } delay:0.3];
    //
    [UIApplication sharedApplication].idleTimerDisabled = YES;//防止锁屏
}

- (void)clickedDiy
{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    //
    RecordOperationBubbleViewController* recordBubbleVC = [[RecordOperationBubbleViewController alloc] init];
    recordBubbleVC.followView = self.myDiy;
    [recordBubbleVC showRecordOperationBubbleViewWithParentVC:self ClickButton:^BOOL(ClickButtonType buttonType) {
        if (buttonType == ClickButtonType_Play) {
            if ([[NetSyncRecord shareSingle] isBookRecordExistWithUid:uinfo.uid BookId:self.bookid]) {
                [[NetSyncRecord shareSingle] downloadRecordsWithWithUid:uinfo.uid BookId:self.bookid oneCompletionHandler:nil allComplete:nil];
                [self playDiy];
            }else{
                [[NetSyncRecord shareSingle] downloadRecordsWithWithUid:uinfo.uid BookId:self.bookid oneCompletionHandler:^(NSURLResponse *response, NSURL *filePath, NSInteger currentPage, NSArray *alreadyDoneArray, NSError *error) {
                    if (alreadyDoneArray.count == 1) {
                        [self playDiy];
                    }
                } allComplete:nil];
            }
            //阅读统计
            [[DBHelper shareInstance] addReadInfo_bookReadMode:self.bookid mode:RMode_diyAudio];
            //
            return YES;
        }else if (buttonType == ClickButtonType_Delete){
            [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"msgRealDelBookRec") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
                    [[TLSoundPlayer shareSingle] stopAllFiles];
                    [[NetSyncRecord shareSingle] deleteBookRecordsWithUid:uinfo.uid BookId:self.bookid];
                    [self.hangMenus setMenuViewArr:@[self.readToMe,self.readMySelf]];
                }
            } buttonTitles:ReadLocalizedString(@"cancel"),ReadLocalizedString(@"sure"),nil];
            return YES;
        }else{
//            UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
//            if (uinfo.isGuest_exp_device) {
//                self.lastUid = uinfo.uid;
//                [[RootViewController shareLastInstance] yzt_Login:NO formVC:self];
//                return NO;
//            }else{
                [self shareContainExlpore];
                return YES;
//            }
        }
    } ClickEmpty:^BOOL{
        return YES;
    }];
    
    //statistical统计
    [self msgTo_menthed:@"statistical_ToolsClicked:" refs:@[@"DIY"] needReturnValue:NO];
}

-(void)shareContainExlpore{
    //
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;

    [[NetSyncRecord shareSingle] synaNetRecordsListWithUid:uinfo.uid BookId:self.bookid Success:^(NSArray *listArray) {
        if (![[NetSyncRecord shareSingle] isNeedSyanRecordWithUid:uinfo.uid BookId:self.bookid]) {
            [self shareRecord];
        }else{
            [[NetSyncRecord shareSingle] synaOffLineDataWithUid:uinfo.uid AllComplete:^{
                [self shareRecord];
            } Failure:^(NSError *error) {
                [self showShareFailAlertView];
            }];
        }
    } Failure:^(NSError *error) {
        [self showShareFailAlertView];
    }];
}
//分享录音方法
-(void)shareRecord{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSString* userName = uinfo.userName;
    if (!userName || userName.length < 1) {
        userName = [NSString stringWithFormat:@"User_%@",uinfo.uCode];
    }
    NSArray* imageArray = @[[UIImage imageNamed:@"public_share_default_icon.png"]];
    if (self.coverImg) {
        imageArray = @[self.coverImg];
    }
    //
    NSString* shareUrl = JRRecordShare_URL(@(uinfo.uid), @(self.bookid), uinfo.country_code);
    [[ShareManager shareManager] JRShareContainExplorWithText:[NSString stringWithFormat:ReadLocalizedString(@"reocrdShareText"),userName,self.bookName] ImageArray:imageArray Url:[NSURL URLWithString:shareUrl] Title:[NSString stringWithFormat:ReadLocalizedString(@"reocrdShareTitle"),userName] Type:SSDKContentTypeAuto BaseView:self.myDiy BookId:self.bookid Success:^(NSDictionary *retDict) {
        //
        [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:YES ActCode:ActCode_ReadVCShareSuccess Param:[NSString stringWithFormat:@"%@inter",@(self.bookid)]];
        //
        [self showShareSuccessAlterViewWithDict:retDict];
    } failure:^(NSError *error) {
        [self showShareFailAlertView];
    } statusChange:^(SSDKResponseState state, SSDKPlatformType type) {
        if (state == SSDKResponseStateBegin) {
            [[WaWaYaYaRewardManager defaultManager] logRewardEventIsNeedHandle:YES ActCode:ActCode_ReadVCShareSuccess Param:[NSString stringWithFormat:@"%@outer",@(self.bookid)]];
        }
    }];
}

-(void)showShareSuccessAlterViewWithDict:(NSDictionary*)retDict{
    NSString* url = retDict[@"gotoUrl"];
    [DataProcessing do_Main:^{
        [UIAlertView tl_showTitle:@"" message:ReadLocalizedString(@"shareMyDiySuccess") didClick:^(UIAlertView * _Nullable alertView, NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                if (url.length) {
                    [DataProcess do_Main:^{
                        WebViewController *webVC = [[WebViewController alloc] init];
                        if (url.length>0) {
                            webVC.url = url;
                            webVC.showType = SettingShowType_H5;
                            webVC.popUpType = WebPopUpType_Present;
                            webVC.isfullScrean = YES;
                            [self presentViewController:webVC animated:YES completion:nil];
                        }
                    } delay:0.3];
                }
            }
        } buttonTitles:ReadLocalizedString(@"xianbuqu"),ReadLocalizedString(@"qukankan"),nil];
    } delay:0.3];
}



-(void)showShareFailAlertView{
    [DataProcessing do_Main:^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ReadLocalizedString(@"talkSharefail")
                                                        message:nil
                                                       delegate:nil
                                              cancelButtonTitle:ReadLocalizedString(@"sure")
                                              otherButtonTitles:nil, nil];
        [alert show];
    } delay:0.3];
}





@end
